package pokerclient.core.network;

import java.io.IOException;

import common.Message;

import pokerclient.core.ClientModel;

/**
 * A class which once every second requests updates from the server.
 * 
 * @author M�rten
 * 
 */
public class Pinger extends Thread {

	/**
	 * Class variables
	 */
	private boolean isPingTime = false; // is it should ping or not
	private int pingInterval = 1000; // interval (default 1 second)
	private static final Message pingMessage = new Message("Client", 0,
			"Pinged you."); // the message to send each interval

	/**
	 * Run the thread. (start the pinger)
	 */
	public void run() {
		while (true) {
			isPingTime = true;
			try {
				Thread.sleep(pingInterval);
			} catch (InterruptedException e) {
				// Do nothing.
			}
			if (isPingTime) {
				try {
					ClientModel.getInstance().sendMessage(pingMessage, false);
				} catch (IOException e) {
					// The server has stopped responding, stop pinging:
					try {
						this.join();
					} catch (InterruptedException e1) {
						// We should not end up in here
					}
				}
			}
		}
	}
}